package com.tongcao.cn.netty.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;

/**
 * @author:tongcao
 * @since:2019/7/8 16:30
 * Description:
 */
public class BioClient {

    public static final int PORT = 8888;

    public static final String ADDRESS = "127.0.0.1";


    public static void main(String[] args) {
        // 模拟10个客户端发送请求
        for (int i = 0; i < 10; i++) {
            mockRequest(i);
        }
    }


    private static void mockRequest(int i) {
        Socket socket = null;
        BufferedReader reader = null;
        PrintWriter writer = null;

        try {
            // Socket 发起连接操作。连接成功后，双方通过输入和输出流进行同步阻塞式通信
            socket = new Socket(ADDRESS, PORT);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取返回内容
            writer = new PrintWriter(socket.getOutputStream(), true);

            String[] opt = {"+", "-", "*", "/"};
            final Random random = new Random(System.currentTimeMillis());
            final String exp = random.nextInt(10) + opt[random.nextInt(4)] + random.nextInt(10) + 1;

            writer.println(exp);// 向服务器端发送数据
            System.out.println(i + "客户端打印返回数据 :" + reader.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                }
                if (null != socket) {
                    socket.close();
                    socket = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}